package com.kws.tool.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.core.domain.R;
import com.kws.common.core.enums.ModelOpType;
import com.kws.common.core.sys.Ksys;
import com.kws.common.core.utils.KConstants;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.tool.dto.CreateElectrovalenceRq;
import com.kws.tool.dto.QueryElectrovalenceRq;
import com.kws.tool.dto.UpdateElectrovalenceRq;
import com.kws.tool.entity.TbElectrovalence;
import com.kws.tool.mapper.ElectrovalenceManagementMapper;
import com.kws.tool.service.ElectrovalenceManagementService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <b>ElectrovalenceManagementServiceImpl</b>
 *
 * @description: ElectrovalenceManagementServiceImpl <br>
 * @date: 2024/11/21 10:21 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class ElectrovalenceManagementServiceImpl extends ServiceImpl<ElectrovalenceManagementMapper, TbElectrovalence> implements ElectrovalenceManagementService {
    private static final Logger logger = LoggerFactory.getLogger(ElectrovalenceManagementServiceImpl.class);

    @Override
    public Page<TbElectrovalence> queryElectrovalencePage(QueryElectrovalenceRq rq) {
        Page<TbElectrovalence> page = new Page<>(rq.getPageNum(), rq.getPageSize());
        Page<TbElectrovalence> pageIno = baseMapper.queryElectrovalencePage(page,rq);
        return pageIno;
    }

    @Override
    public boolean createElectrovalence(CreateElectrovalenceRq rq) {
        TbElectrovalence tbElectrovalence = new TbElectrovalence();
        BeanUtil.copyProperties(rq,tbElectrovalence);
        Ksys.setBasicModelData(tbElectrovalence, SecurityUtils.getStringUserId(), KConstants.DATA_ENABLE, ModelOpType.CREATE);
        int insert = baseMapper.insert(tbElectrovalence);
        if (1 == insert){
            return true;
        }
        return false;
    }

    @Override
    public TbElectrovalence queryElectrovalenceById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean updateElectrovalence(UpdateElectrovalenceRq rq) {
        TbElectrovalence tbElectrovalence = baseMapper.selectById(rq.getId());
        BeanUtil.copyProperties(rq,tbElectrovalence);
        Ksys.setBasicModelData(tbElectrovalence,SecurityUtils.getStringUserId(),KConstants.DATA_ENABLE,ModelOpType.UPDATE);
        int i = baseMapper.updateById(tbElectrovalence);
        if (1 == i){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteElectrovalenceById(Long id) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("enable","0");
        updateWrapper.set("update_user",SecurityUtils.getStringUserId());
        updateWrapper.set("update_time",new Date());
        int update = baseMapper.update(null, updateWrapper);
        if (1 == update){
            return true;
        }
        return false;
    }

    @Override
    public R uploadElectrovalence(MultipartFile file,String type) throws IOException {
        List<TbElectrovalence> electrovalenceList = new ArrayList<>();
        try {
            InputStream ins = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(ins);
            List<Sheet> sheets = reader.getSheets();
            //解析商业用电上传电价数据
            if ("1".equals(type)){
                for (Sheet sheet : sheets) {
                    reader.setSheet(sheet);
                    List<List<Object>> read = reader.read();
                    // 从第三行开始读取
                    AtomicInteger i= new AtomicInteger();
                    read.forEach(column -> {
                        if (i.getAndIncrement() < 1){
                            return;
                        }
                        TbElectrovalence electrovalence = new TbElectrovalence();
                        if (!String.valueOf(column.get(0)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(0)))) {
                            electrovalence.setElectricityAddress(String.valueOf(column.get(0)));
                        }
                        if (!String.valueOf(column.get(1)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(1)))) {
                            electrovalence.setDate(String.valueOf(column.get(1)));
                        }
                        if (!String.valueOf(column.get(2)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(2)))) {
                            electrovalence.setElectricityType1(String.valueOf(column.get(2)));
                        }
                        if (!String.valueOf(column.get(3)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(3)))) {
                            electrovalence.setElectricityType(String.valueOf(column.get(3)));
                        }
                        if (!String.valueOf(column.get(4)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(4)))) {
                            electrovalence.setVoltageLevel(String.valueOf(column.get(4)));
                        }
                        if (!String.valueOf(column.get(5)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(5)))) {
                            electrovalence.setNeedleElectrovalence(new BigDecimal(String.valueOf(column.get(5))));
                        }else {
                            electrovalence.setNeedleElectrovalence(BigDecimal.ZERO);
                        }
                        if (!String.valueOf(column.get(6)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(6)))) {
                            electrovalence.setPeakElectrovalence(new BigDecimal(String.valueOf(column.get(6))));
                        }else {
                            electrovalence.setPeakElectrovalence(BigDecimal.ZERO);
                        }
                        if (!String.valueOf(column.get(7)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(7)))) {
                            electrovalence.setFlatSectionElectrovalence(new BigDecimal(String.valueOf(column.get(7))));
                        }else {
                            electrovalence.setFlatSectionElectrovalence(BigDecimal.ZERO);
                        }
                        if (!String.valueOf(column.get(8)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(8)))) {
                            electrovalence.setLowEbbElectrovalence(new BigDecimal(String.valueOf(column.get(8))));
                        }else {
                            electrovalence.setLowEbbElectrovalence(BigDecimal.ZERO);
                        }
                        if (!String.valueOf(column.get(9)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(9)))) {
                            electrovalence.setRavineElectrovalence(new BigDecimal(String.valueOf(column.get(9))));
                        }else {
                            electrovalence.setRavineElectrovalence(BigDecimal.ZERO);
                        }
                        if (!String.valueOf(column.get(10)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(10)))) {
                            electrovalence.setCapacityElectrovalence(new BigDecimal(String.valueOf(column.get(10))));
                        }else {
                            electrovalence.setCapacityElectrovalence(BigDecimal.ZERO);
                        }
                        if (!String.valueOf(column.get(11)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(11)))) {
                            electrovalence.setDemandElectrovalence(new BigDecimal(String.valueOf(column.get(11))));
                        }else {
                            electrovalence.setDemandElectrovalence(BigDecimal.ZERO);
                        }
                        Ksys.setBasicModelData(electrovalence,SecurityUtils.getStringUserId(),KConstants.DATA_ENABLE,ModelOpType.CREATE);
                        electrovalenceList.add(electrovalence);
                    });
                }
            }
            //解析居民用电上传数据
            else if ("0".equals(type)){
                List<List<Object>> read = reader.read();
                // 从第三行开始读取
                AtomicInteger i= new AtomicInteger();
                read.forEach(column -> {
                    if (i.getAndIncrement() < 1) {
                        return;
                    }
                    TbElectrovalence electrovalence = new TbElectrovalence();
                    if (!String.valueOf(column.get(0)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(0)))) {
                        electrovalence.setElectricityType(String.valueOf(column.get(0)));
                    }
                    if (!String.valueOf(column.get(1)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(1)))) {
                        electrovalence.setElectricityAddress(String.valueOf(column.get(1)));
                    }
                    if (!String.valueOf(column.get(2)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(2)))) {
                        if ("分时计价".equals(String.valueOf(column.get(2)))){
                            electrovalence.setPricingMethod("0");
                        }else if ("阶梯计价".equals(String.valueOf(column.get(2)))){
                            electrovalence.setPricingMethod("1");
                        }
                    }
                    if (!String.valueOf(column.get(3)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(3)))) {
                        electrovalence.setFirstStepElectricQuantity(Integer.getInteger(String.valueOf(column.get(3))));
                    }
                    if (!String.valueOf(column.get(4)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(4)))) {
                        electrovalence.setFirstStepElectrovalence(new BigDecimal(String.valueOf(column.get(4))));
                    }else {
                        electrovalence.setFirstStepElectrovalence(BigDecimal.ZERO);
                    }
                    if (!String.valueOf(column.get(5)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(5)))) {
                        electrovalence.setSecondStepElectricQuantity(Integer.getInteger(String.valueOf(column.get(5))));
                    }
                    if (!String.valueOf(column.get(6)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(6)))) {
                        electrovalence.setSecondStepElectrovalence(new BigDecimal(String.valueOf(column.get(6))));
                    }else {
                        electrovalence.setSecondStepElectrovalence(BigDecimal.ZERO);
                    }
                    if (!String.valueOf(column.get(7)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(7)))) {
                        electrovalence.setThirdStepElectricQuantity(Integer.getInteger(String.valueOf(column.get(7))));
                    }
                    if (!String.valueOf(column.get(8)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(8)))) {
                        electrovalence.setThirdStepElectrovalence(new BigDecimal(String.valueOf(column.get(8))));
                    }else {
                        electrovalence.setThirdStepElectrovalence(BigDecimal.ZERO);
                    }
                    Ksys.setBasicModelData(electrovalence,SecurityUtils.getStringUserId(),KConstants.DATA_ENABLE,ModelOpType.CREATE);
                    electrovalenceList.add(electrovalence);
                });
            }

            if (CollectionUtil.isNotEmpty(electrovalenceList)){
                this.saveBatch(electrovalenceList);
            }
        }catch (Exception e){
            return R.fail("上传数据异常,文件解析异常");
        }

        return R.ok(true);
    }

    @Override
    public R queryElectricityTypeList(String electricityType) {
        List<String> electricityTypeList = baseMapper.queryElectricityTypeList(electricityType);
        if (CollectionUtil.isNotEmpty(electricityTypeList)){
            return R.ok(electricityTypeList.stream().distinct().collect(Collectors.toList()));
        }
        return R.ok(electricityTypeList);
    }

    @Override
    public R queryVoltageLevelList(String voltageLevel) {
        List<String> voltageLevelList = baseMapper.queryVoltageLevelList(voltageLevel);
        if (CollectionUtil.isNotEmpty(voltageLevelList)){
            return R.ok(voltageLevelList.stream().distinct().collect(Collectors.toList()));
        }
        return R.ok(voltageLevelList);
    }
}
